package cn.datawin.dockerclient.controller;

import cn.datawin.bms.deploy.entity.DeplBranchInfoEntity;
import cn.datawin.bms.deploy.entity.DeplDockerInfoEntity;
import cn.datawin.bms.deploy.entity.DeplModuleInfoEntity;
import cn.datawin.common.core.util.R;
import cn.datawin.constant.DOCKER;
import cn.datawin.dockerclient.docker.DockerDeployService;
import cn.datawin.dockerclient.dto.ActiveDto;
import cn.datawin.dockerclient.service.DeplBranchInfoService;
import cn.datawin.dockerclient.service.DeplDockerInfoService;
import cn.datawin.dockerclient.service.DeplModuleInfoService;
import cn.datawin.dockerclient.service.DeplServerModuleInfoService;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * docker 容器的管理
 *
 * @author shengdongcloud
 * @date 2025-03-13 11:10:30
 */
@RequiredArgsConstructor
@Slf4j
@RestController
public class DockerController {

	private final DeplBranchInfoService deplBranchInfoService;
	private final DeplModuleInfoService deplModuleInfoService;

	private final DeplServerModuleInfoService deplServerModuleInfoService;
	private final DockerDeployService dockerDeployService;
	private final DeplDockerInfoService deplDockerInfoService;

	@RequestMapping(value = "/test",  name = "测试")
	public R test() {
		return R.ok(1);
	}
	/**
	 * 激活发布一个容器
	 * @param activeDto 激活信息
	 *
	 */
	@RequestMapping(value = "/active", method = RequestMethod.POST, name = "激活某一个镜像")
	public R active(@RequestBody ActiveDto activeDto) {

		 int moduleId = activeDto.getModuleId();
		 int branchId = activeDto.getBranchId();
		 String containerName = activeDto.getContainerName();
		 String configJson = activeDto.getConfigJson();
		 String serverIp = activeDto.getServerIp();
		 String serverPort = activeDto.getServerPort();

		log.info("开始激活容器----{}", JSON.toJSONString(activeDto));
		int dockerInfoId;
		//检查container_name
		//销毁的容器不用考虑
		boolean check = dockerDeployService.check(containerName, serverIp);
		if (check) {
			log.info("容器检查通过" + containerName);
			//获取分支信息
			DeplBranchInfoEntity branchInfo = deplBranchInfoService.getById(branchId);
			//获取模块信息
			DeplModuleInfoEntity moduleInfo = deplModuleInfoService.getById(moduleId);
			//开始激活
			try {
				String cid = dockerDeployService.active(moduleInfo.getName(), branchInfo, containerName, configJson, serverIp, serverPort);
				//保存docker_info记录
				DeplDockerInfoEntity deplDockerInfoEntity = new DeplDockerInfoEntity();
				deplDockerInfoEntity.setBranchId(branchId);
				deplDockerInfoEntity.setConfigJson(configJson);
				deplDockerInfoEntity.setModuleId(moduleId);
				deplDockerInfoEntity.setContainerName(containerName);
				deplDockerInfoEntity.setInnerServerPort(serverPort);
				deplDockerInfoEntity.setOutServerPort(serverPort);
				deplDockerInfoEntity.setServerIp(serverIp);
				deplDockerInfoEntity.setContainerId(cid);
				deplDockerInfoEntity.setStatus(DOCKER.STATUS.RUNNING);
				deplDockerInfoEntity.setUpdatetime(LocalDateTime.now());
				deplDockerInfoService.save(deplDockerInfoEntity);
				dockerInfoId = deplDockerInfoEntity.getId();
				//更新server_module_info表
				deplServerModuleInfoService.updateServerModuleInfo(moduleId, serverIp, serverPort, 1);
				String msg = "容器激活成功" + containerName + " dockerid 为 " + dockerInfoId;
				log.info(msg);
				return R.ok(dockerInfoId).setMsg(msg);
			} catch (Exception e) {
				e.printStackTrace();
				String msg = "容器激活失败" + containerName;
				log.error(msg,e);
				return R.failed(msg);
			}
		} else {
			//-1表示重复了
			String msg = "容器检查失败，容器名重复" + containerName;
			log.info(msg);
			return R.failed(msg);
		}
	}

	@RequestMapping(value = "/stop", method = RequestMethod.GET, name = "停止某一个容器")
	public R stop(@RequestParam int dockerinfo_id) {
		try {
			dockerDeployService.stop(dockerinfo_id);
			String msg = "容器停止成功： " + dockerinfo_id;
			log.info(msg);
			return R.ok().setMsg(msg);
		} catch (Exception e) {
			String msg = "容器停止失败： " + dockerinfo_id;
			log.error(msg,e);
			return R.failed(msg);
		}
	}

	@RequestMapping(value = "/restart", method = RequestMethod.POST, name = "重新开始某一个容器")
	public R restart(@RequestParam int dockerinfo_id) {
		try {
			dockerDeployService.restart(dockerinfo_id);
			String msg = "容器重新启动成功： " + dockerinfo_id;
			log.info(msg);
			return R.ok().setMsg(msg);
		} catch (Exception e) {
			String msg = "容器重新启动失败： " + dockerinfo_id;
			log.error(msg,e);
			return R.failed(msg);
		}
	}

	@RequestMapping(value = "/remove", method = RequestMethod.POST, name = "销毁某一个容器")
	public R remove(@RequestParam int dockerinfo_id) {
		try {
			dockerDeployService.remove(dockerinfo_id);
			String msg = "容器销毁成功： " + dockerinfo_id;
			log.info(msg);
			return R.ok().setMsg(msg);
		} catch (Exception e) {
			String msg = "容器销毁失败： " + dockerinfo_id;
			log.error(msg,e);
			return R.failed(msg);
		}
	}
	/**
	 * 复活发布一个容器
	 *
	 * @param dockerinfo_id      dockerinfo_id
	 */
	@RequestMapping(value = "/reborn", method = RequestMethod.POST, name = "激活某一个镜像")
	public R active(@RequestParam int dockerinfo_id) {
		log.info("开始复活容器----{}", dockerinfo_id);
		int dockerid;
		DeplDockerInfoEntity dockerInfo = deplDockerInfoService.getById(dockerinfo_id);
		String containerName = dockerInfo.getContainerName();
		String serverIp = dockerInfo.getServerIp();
		String serverPort = dockerInfo.getOutServerPort();
		Integer branchId = dockerInfo.getBranchId();
		Integer moduleId = dockerInfo.getModuleId();
		String configJson = dockerInfo.getConfigJson();
		//检查container_name
		//销毁的容器不用考虑
		boolean check = dockerDeployService.check(containerName, serverIp);
		if (check) {
			log.info("容器检查通过" + containerName);
			//获取分支信息
			DeplBranchInfoEntity branchInfo = deplBranchInfoService.getById(branchId);
			//获取模块信息
			DeplModuleInfoEntity moduleInfo = deplModuleInfoService.getById(moduleId);
			//开始激活
			try {
				String cid = dockerDeployService.active(moduleInfo.getName(), branchInfo, containerName, configJson, serverIp, serverPort);
				//保存结果
				DeplDockerInfoEntity deplDockerInfoEntity = new DeplDockerInfoEntity();
				deplDockerInfoEntity.setId(dockerinfo_id);
				deplDockerInfoEntity.setContainerId(cid);
				deplDockerInfoEntity.setStatus(DOCKER.STATUS.RUNNING);
				deplDockerInfoEntity.setUpdatetime(LocalDateTime.now());
				deplDockerInfoService.updateById(deplDockerInfoEntity);
				dockerid = deplDockerInfoEntity.getId();
				String msg = "容器复活成功" + containerName + " dockerid 为 " + dockerid;
				log.info(msg);
				return R.ok(dockerid).setMsg(msg);
			} catch (Exception e) {
				e.printStackTrace();
				String msg = "容器复活失败" + containerName;
				log.error(msg,e);
				return R.failed(msg);
			}
		} else {
			//-1表示重复了
			String msg = "容器检查失败，容器名重复" + containerName;
			log.info(msg);
			return R.failed(msg);
		}
	}

/*

	@RequestMapping(value = "/restart", method = RequestMethod.POST, name = "重新开始某一个容器")
	public R restart(@RequestParam int dockerinfo_id) {
		try {
			dockerDeployService.restart(dockerinfo_id);
			String msg = "容器重新启动成功： " + dockerinfo_id;
			log.info(msg);
			return R.ok().setMsg(msg);
		} catch (Exception e) {
			String msg = "容器重新启动失败： " + dockerinfo_id;
			log.error(msg,e);
			return R.failed(msg);
		}
	}

	@RequestMapping(value = "/inspectRun", method = RequestMethod.POST, name = "检查一个容器是否在运行")
	public R inspectRun(@RequestParam int dockerinfo_id) {
		//-1 报错 1 运行中 0 停止了
		int status = -1;
		try {
			boolean run = dockerDeployService.inspectRun(dockerinfo_id);
			status = run ? 1 : 0;
			String msg = "容器运行状态为： " + dockerinfo_id + " 运行状态为: " + run;
			log.info(msg);
			return R.ok(status).setMsg(msg);
		} catch (Exception e) {
			String msg = "容器检测失败： " + dockerinfo_id;
			log.error(msg,e);
			return R.failed(msg);
		}
	}


	@RequestMapping(value = "/getMemStats", method = RequestMethod.POST, name = "获取内存信息")
	public R getMemStats(@RequestParam int dockerId) {
		try {
			JSONObject result = dockerDeployService.getMemStats(dockerId);
			return R.ok(result);
		} catch (Exception e) {
			String msg = "获取内存信息异常";
			log.error(msg, e);
			return R.failed(msg);
		}
	}

	@RequestMapping(value = "/getLogsList", method = RequestMethod.POST, name = "获取日志信息")
	public R getLogsList(@RequestParam int dockerId) {
		try {
			List<String> resList = dockerDeployService.getLogsList(dockerId);
			return R.ok(resList);
		} catch (Exception e) {
			String msg = "获取日志信息异常";
			log.error(msg, e);
			return R.failed(msg);
		}
	}
*/
}
